import { Injectable } from '@angular/core';
import { Location } from '@angular/common';
import { Http, Request, RequestOptionsArgs, RequestMethod, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Rx';

import { LoadingAnimateService } from '../common/loading';
import { AuthService } from '../auth';

@Injectable()
export class HttpService {
    baseURL = 'http://127.0.0.1:8080/v1';

    private jsonHeaders = new Headers({ 'Content-Type': 'application/json' });

    constructor(
        private http: Http,
        private location: Location,
        private loadingService: LoadingAnimateService,
        private authService: AuthService
    ) { }

    // 获取请求的url
    private getRequestURL(url: string): string {
        if (url.charAt(0) !== '/') {
            return `${this.baseURL}/${url}`;
        }
        return `${this.baseURL}${url}`;
    }

    // 解析响应数据
    private extractData(res: Response) {
        const body = res.json();
        return body;
    }

    // 处理响应错误
    private handleError(error: Response | any) {
        let errMsg: string;
        let errCode: number;
        if (error instanceof Response) {
            let err: string;
            try {
                const body = error.json();
                err = body.message;
                errCode = body.code;
            } catch (e) {
                err = '';
            }
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }

        console.error(`http error - ${errCode} - ${errMsg}`);
        this.loadingService.setValue(false);

        return Promise.reject(errMsg);
    }

    // post请求
    postJSON<T>(url: string, body: any): Promise<T> {
        const options = new RequestOptions({
            method: RequestMethod.Post,
            body: JSON.stringify(body),
            headers: this.jsonHeaders
        });

        return this.request<T>(this.getRequestURL(url), options);
    }

    // get请求
    getJSON<T>(url: string, search?: Map<string, string>): Promise<T> {
        const params = new URLSearchParams();
        if (search) {
            search.forEach((v, i) => {
                params.set(i, v);
            });
        }

        const options = new RequestOptions({
            method: RequestMethod.Get,
            search: params
        });

        return this.request<T>(this.getRequestURL(url), options);
    }
    // put请求
    putJSON<T>(url: string, body: any): Promise<T> {
        console.log(url);
        const options = new RequestOptions({
            method: RequestMethod.Put,
            body: JSON.stringify(body),
            headers: this.jsonHeaders
        });

        return this.request<T>(this.getRequestURL(url), options);
    }

    // delete请求
    deleteJSON<T>(url: string): Promise<T> {
        const options = new RequestOptions({
            method: RequestMethod.Delete,
            headers: this.jsonHeaders
        });
        return this.request<T>(this.getRequestURL(url), options);
    }

    // 请求处理
    request<T>(url: string, options?: RequestOptionsArgs): Promise<T> {



        if (this.authService.isLoggedIn) {
            let tooken = this.authService.sessionID
            if (!options.headers) {
                //595d9a541d41c80523b4cb5c 69b99ef80c23aab002791af6cb38dcdbf2e72e9e
                options.headers = new Headers({ 'Authorization': 'Bearer ' + tooken });
            } else {
                options.headers.set("Authorization", "Bearer " + tooken)
            }
        }
        return this.http.request(url, options)
            .toPromise()
            .then(this.extractData)
            .catch((error: Response | any) => {
                let errMsg: string;
                let errCode: number;
                if (error instanceof Response) {
                    let err: string;
                    try {
                        const body = error.json();
                        err = body["msg"];
                        //errCode = body.code;
                    } catch (e) {
                        err = '';
                    }
                    errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
                } else {
                    errMsg = error.message ? error.message : error.toString();
                }

                this.loadingService.setValue(false); // 隐藏等待动画
                console.error(errMsg);

                return Promise.reject(errMsg);
            });
    }
}
